package com.myjunit.ldap;

import java.util.Enumeration;
import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;


public class LdapUtils {

	private static DirContext ctx = null;

	/**
	 * 获取LDAP连接
	 * 
	 * @return LDAP连接
	 * @throws NamingException
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static DirContext getCtxWithRoot() throws NamingException {

		DirContext dirCtx = null;
		Hashtable env = new Hashtable();
		env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
		env.put(Context.PROVIDER_URL, "ldap://" + LdapConstants.LDAP_HOST + ":" + LdapConstants.LDAP_PORT + "/");
		env.put(Context.SECURITY_AUTHENTICATION, "simple"); //认证方式
		env.put(Context.SECURITY_PRINCIPAL, LdapConstants.LDAP_USER_ROOT); 
		env.put(Context.SECURITY_CREDENTIALS, LdapConstants.LDAP_USER_ROOT_PAW);
		try {
			dirCtx = new InitialDirContext(env);
		} catch (Exception e) {
			// logger.error("连接到LDAP失败，程序继续执行", e);
			throw new RuntimeException("连接到LDAP失败，程序继续执行" + e.getMessage());
		}
		return dirCtx;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static DirContext getCtx(String userName, String password) throws NamingException {

		String root = LdapConstants.LDAP_CN + "," + LdapConstants.LDAP_ROOT; // root
		String uid = "uid=" + userName + "," + LdapConstants.LDAP_CN + "," + LdapConstants.LDAP_ROOT;
		
		Hashtable env = new Hashtable();
		env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
		env.put(Context.PROVIDER_URL, "ldap://" + LdapConstants.LDAP_HOST + ":" + LdapConstants.LDAP_PORT + "/" + root);
		env.put(Context.SECURITY_AUTHENTICATION, "simple");
//		env.put(Context.SECURITY_PRINCIPAL, uid);
//		env.put(Context.SECURITY_PRINCIPAL, "uid=zhaoxin,cn=users,DC=clpc,DC=com");
		env.put(Context.SECURITY_PRINCIPAL, "cn=root");
		env.put(Context.SECURITY_CREDENTIALS, password);

		ctx = new InitialDirContext(env);

		return ctx;
	}

	/**
	 * 通过用户名和密码判断是否允许通过
	 */
	public static boolean loginAuthorize(String userName, String password) {
		boolean bAuthorized = false;
		DirContext ctx = null;
		try {
			ctx = getCtx(userName, password);
		} catch (NamingException e) {
//			e.printStackTrace();
		}
		if (ctx != null)
			bAuthorized = true;
		return bAuthorized;
	}

	/**
	 * 关闭ldap连接
	 */
	private static void closeCtx() {
		try {
			if (ctx != null) {
				ctx.close();
			}
		} catch (NamingException ex) {
			// logger.error(null, ex);
		}
	}

	@SuppressWarnings("rawtypes")
	public static String getUserAttributeValue(String userName, String attribute) {
		String ret_departCode = "";
		DirContext dirCtx = null;
		String dirRoot = "uid=" + userName + "," + LdapConstants.LDAP_CN + "," + LdapConstants.LDAP_ROOT;
		String query = "objectclass=*";
		try {
			dirCtx = getCtxWithRoot();
			SearchControls ctrl = new SearchControls();
			ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE);
			NamingEnumeration enumeration = dirCtx.search(dirRoot, query, ctrl);
			if (enumeration.hasMore()) {
				SearchResult result = (SearchResult) enumeration.next();
				Attributes attribs = result.getAttributes();
				if (attribs == null) {
					System.out.println("No attributes");
				} else {
					// 对查询到每个条目进行分析
					for (NamingEnumeration ae = attribs.getAll(); ae.hasMoreElements();) {
						Attribute attr = (Attribute) ae.next();
						String attrId = attr.getID();
						// 对条目的属性进行分析
						for (Enumeration vals = attr.getAll(); vals.hasMoreElements(); System.out.println(attrId + ": "
								+ vals.nextElement()));
					}
				}

			}

		} catch (Exception e) {
			return "";
		} finally {
			// try {
			// if (dirCtx != null) {
			// dirCtx.close();;
			// }
			// } catch (NamingException e) {
			// e.printStackTrace();
			// }
		}
		return ret_departCode;
	}

	public static void main(String[] args) {

		LdapUtils ldaptt = new LdapUtils();
		if (loginAuthorize("zhaoxin", "password")) {
			// if(loginAuthorize("wangchangtao", "password")){
			// ldaptt.getUserAttributeValue("yangxiaolei", "cn");
			// ldaptt.getUserAttributeValue("zhaoxin", "aaa");
			
			//获得用户相关信息
//			ldaptt.getUserAttributeValue("zhaoxin", "password");
			System.out.println("认证通过");
		} else {
			System.out.println("认证失败");
		}

	}
}
